﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;
using PhoneDBModel;
/// <summary>
/// Summary description for PhoneService
/// </summary>
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class PhoneService : System.Web.Services.WebService
{

    public PhoneService()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public XmlNode GetPhoneSession(string sessionUID)
    {
        XmlDocument d = new XmlDocument();
        d.AppendChild(d.CreateElement("PhoneSession"));

        if (!string.IsNullOrEmpty(sessionUID) && sessionUID.Length == 32)
        {
            try
            {
                XmlElement root = d.DocumentElement;

                PhoneDBEntities dbe = new PhoneDBEntities();
                DateTime exp = DateTime.Now.AddHours(-1);
                CallRequest cr = dbe.CallRequests.Where(u => u.Code == sessionUID && u.Timestamp > exp).FirstOrDefault();

                if (cr != null)
                {
                    XmlAttribute phone = d.CreateAttribute("companyPhone");
                    phone.Value = cr.Phone;
                    root.Attributes.Append(phone);

                    XmlAttribute disconnect = d.CreateAttribute("disconnectAfter");
                    disconnect.Value = cr.MaxDuration.ToString();
                    root.Attributes.Append(disconnect);
                }
                else
                {
                    log.Logging("PhoneSessionNotFound :" + sessionUID);
                    SetXmlNotAllowed(d.DocumentElement, Errors.PhoneSessionNotFound);
                }

            }
            catch (Exception ex)
            {
                log.Logging(ex);
                SetXmlNotAllowed(d.DocumentElement, Errors.WebserviceException);
            }
        }
        else
        {
            SetXmlNotAllowed(d.DocumentElement, Errors.MissingParameters);
        }
        return d;
    }

    [WebMethod]
    public void LogCall(string Extension, string Phone, DateTime StartDate, int Duration)
    {
        PhoneDBEntities dbe = new PhoneDBEntities();
        CallRequest cr = dbe.CallRequests.Where(u => u.Code == Extension).FirstOrDefault();
        if (cr != null)
        {
            string country = CheckPhoneNumber.GetCountry(cr.Phone);

            Price pr = dbe.Prices.Where(x => x.Code == country).FirstOrDefault();
            decimal? cost = 0;
            if (pr != null)
            {
                cost = pr.CPM * ((decimal)Duration / 60);
            }
            CallLog cl = new CallLog();
            cl.Duration = Duration;
            cl.Cost = cost;
            cl.PhoneCalled = Phone;
            cl.Timestamp = StartDate;
            cl.UserId = 1;
            cl.RequestId = cr.Id;
            dbe.CallLogs.AddObject(cl);
            dbe.SaveChanges();

            AccountBalance ab = dbe.AccountBalances.Where(x => x.Userid == cr.UserId).FirstOrDefault();
            if (ab != null)
            {
                ab.Credit -= (decimal)cost;
            }
            dbe.SaveChanges();
        }
    }

    private static void SetXmlNotAllowed(XmlElement root, Errors reason)
    {
        root.SetAttribute("EnableCall", "false");
        root.SetAttribute("DisconnectAfter", "0");
        root.SetAttribute("Reason", ((int)reason).ToString());
    }

    public enum Errors
    {
        IsOk = 99,
        InvalidPhoneNumber = 100,
        DailyLimitReached = 101,
        MonthLimitReached = 102,
        PhoneOrIPBlacklisted = 103,
        MobilesNotAllowed = 104,
        ClientNotFound = 105,
        MissingParameters = 106,
        WebserviceException = 107,
        PhoneSessionExpired = 108,
        PhoneSessionNotFound = 109,
    }
}
